import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
import { UnitFileBean } from "./bean/unitFile.bean";
import { UploadFile, NzNotificationService } from "ng-zorro-antd";
import { HttpServcie } from "../../../../service/http.service";
import { Config } from "../../../../service/config";
import { Router, ActivatedRoute } from "@angular/router";

@Component({
  selector: "elevator-unit-file",
  templateUrl: "./elevator-unit-file.component.html",
  styleUrls: ["./elevator-unit-file.component.scss"]
})
export class ElevatorUnitFileComponent implements OnInit {
  @Input("inValue") inValue: any;
  @Output("outPut") outPut = new EventEmitter();
  uploadUrl = Config.IP + Config.API.upload; //上传的地址
  unitFileBean = new UnitFileBean();
  elevatorNum; //设备代码
  nextCheckDate; //下次检验日期
  elevatorTypeId;
  elevatorId;
  uploadParam;
  config: any = Config;
  previewImage = "";
  previewVisible = false;
  editFlag: boolean = false;
  inDate: any = {};
  fileCompletePercent : any;
  constructor(
    private _notification: NzNotificationService,
    private httpServcie: HttpServcie,
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
    this.activatedRoute.params.subscribe(data => {
      //深度 clone 一下，否则不能修改
      this.inDate = Object.assign({}, data);
    });
    if (!this.inValue) {
      this.inValue = this.inDate;
    }
  }

  ngOnInit() {
    this.elevatorNum = this.inValue.elevatorNum;
    this.nextCheckDate = this.inValue.nextCheckDate;
    this.elevatorTypeId = this.inValue.elevatorTypeId;
    this.elevatorId = this.inValue.id;
    this.elevatorQuery(this.elevatorNum);

  }

  /**
   * 初始化样图
   */
  initImg(){
    /**
     * 添加样图
     */
    //监督检查报告
    this.unitFileBean.oir = [
      {
        uid: -1,
        name: 'safe1.jpg',
        status: 'done',
        url: 'assets/images/safe1.jpg'
      }
    ];
    //定期检验报告
    this.unitFileBean.pir = [
      {
        uid: -1,
        name: 'safe2.jpg',
        status: 'done',
        url: 'assets/images/safe2.jpg'
      }
    ];

    //日常检查与使用状况记录
    this.unitFileBean.diur = [
      {
        uid: -1,
        name: 'safe3.jpg',
        status: 'done',
        url: 'assets/images/safe3.jpg'
      }
    ];
    //日常维护保养记录
    this.unitFileBean.dmr = [
      {
        uid: -1,
        name: 'safe4.jpg',
        status: 'done',
        url: 'assets/images/safe4.jpg'
      }
    ];
    //年度自行检查记录或者报告
    this.unitFileBean.airr = [
      {
        uid: -1,
        name: 'safe5.jpg',
        status: 'done',
        url: 'assets/images/safe5.jpg'
      }
    ];
    //应急救援记录
    this.unitFileBean.err = [
      {
        uid: -1,
        name: 'safe6.jpg',
        status: 'done',
        url: 'assets/images/safe6.jpg'
      }
    ];
    //运行故障和事故记录
    this.unitFileBean.rfar = [
      {
        uid: -1,
        name: 'safe7.jpg',
        status: 'done',
        url: 'assets/images/safe7.jpg'
      }
    ];
    //安全附件、安全保护装置定期校验报告
    this.unitFileBean.pcsd = [
      {
        uid: -1,
        name: 'safe8.jpg',
        status: 'done',
        url: 'assets/images/safe8.jpg'
      }
    ];
    //使用登记证
    this.unitFileBean.urc = [
      {
        uid: -1,
        name: 'safe9.jpg',
        status: 'done',
        url: 'assets/images/safe9.jpg'
      }
    ];
    //新增：安全检验合格证
    this.unitFileBean.sic = [
      {
        uid: -1,
        name: 'safe10.jpg',
        status: 'done',
        url: 'assets/images/safe10.jpg'
      }
    ];


    /**
     * 制造资料
     */

    //新增：安装使用维护说明书
    this.unitFileBean.imm = [
      {
        uid: -1,
        name: 'safe11.jpg',
        status: 'done',
        url: 'assets/images/safe11.jpg'
      }
    ];
    //电梯轿厢实图
    this.unitFileBean.ecp = [
      {
        uid: -1,
        name: 'safe12.jpg',
        status: 'done',
        url: 'assets/images/safe12.jpg'
      }
    ];
    //制造许可证明文件
    this.unitFileBean.ml = [
      {
        uid: -1,
        name: 'safe13.jpg',
        status: 'done',
        url: 'assets/images/safe13.jpg'
      }
    ];
    //整机型式试验证书
    this.unitFileBean.fttc = [
      {
        uid: -1,
        name: 'safe14.jpg',
        status: 'done',
        url: 'assets/images/safe14.jpg'
      }
    ];
    //产品质量证明文件
    this.unitFileBean.cpq = [
      {
        uid: -1,
        name: 'safe15.jpg',
        status: 'done',
        url: 'assets/images/safe15.jpg'
      }
    ];//门锁装置型式试验合格证
    this.unitFileBean.ttgl = [
      {
        uid: -1,
        name: 'safe16.jpg',
        status: 'done',
        url: 'assets/images/safe16.jpg'
      }
    ];//限速器型式试验合格证
    this.unitFileBean.ttsl = [
      {
        uid: -1,
        name: 'safe17.jpg',
        status: 'done',
        url: 'assets/images/safe17.jpg'
      }
    ];
    //安全钳型式试验合格证
    this.unitFileBean.sctt = [
      {
        uid: -1,
        name: 'safe18.jpg',
        status: 'done',
        url: 'assets/images/safe18.jpg'
      }
    ];
    //缓冲器型式试验合格证
    this.unitFileBean.bttc = [
      {
        uid: -1,
        name: 'safe19.jpg',
        status: 'done',
        url: 'assets/images/safe19.jpg'
      }
    ];
    //含有电子元件的安全电路（如果有）型式试验合格证
    this.unitFileBean.csct = [
      {
        uid: -1,
        name: 'safe20.jpg',
        status: 'done',
        url: 'assets/images/safe20.jpg'
      }
    ];
    //轿厢上行超速保护装置型式试验合格证
    this.unitFileBean.cott = [
      {
        uid: -1,
        name: 'safe21.jpg',
        status: 'done',
        url: 'assets/images/safe21.jpg'
      }
    ];
    //驱动主机型式试验合格证
    this.unitFileBean.dhtt = [
      {
        uid: -1,
        name: 'safe22.jpg',
        status: 'done',
        url: 'assets/images/safe23.jpg'
      }
    ];
    //控制柜型式试验合格证
    this.unitFileBean.cctt = [
      {
        uid: -1,
        name: 'safe23.jpg',
        status: 'done',
        url: 'assets/images/safe24.jpg'
      }
    ];


    //限速器调试证书
    this.unitFileBean.sldc = [
      {
        uid: -1,
        name: 'safe24.jpg',
        status: 'done',
        url: 'assets/images/safe24.jpg'
      }
    ];
    //渐进式安全钳的调试证书
    this.unitFileBean.adc = [
      {
        uid: -1,
        name: 'safe25.jpg',
        status: 'done',
        url: 'assets/images/safe25.jpg'
      }
    ];
    //机房或者机器设备间及井道布置图
    this.unitFileBean.lmrw = [
      {
        uid: -1,
        name: 'safe26.jpg',
        status: 'done',
        url: 'assets/images/safe26.jpg'
      }
    ];
    //电气原理图（含动力电路和连接电气安全装置的电路）
    this.unitFileBean.es = [
      {
        uid: -1,
        name: 'safe27.jpg',
        status: 'done',
        url: 'assets/images/safe27.jpg'
      }
    ];

    /**
     * 安装资料
     */
    this.unitFileBean.ipt = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe28.jpg'
      }
    ];

    this.unitFileBean.inn = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe29.jpg'
      }
    ];

    this.unitFileBean.cpei = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe30.jpg'
      }
    ];

    this.unitFileBean.icpr = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe31.jpg'
      }
    ];
    this.unitFileBean.srei = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe32.jpg'
      }
    ];
    this.unitFileBean.icdc = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe33.jpg'
      }
    ];
    this.unitFileBean.iqd = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe34.jpg'
      }
    ];

    /**
     * 改造或重大修理资料
     */
    this.unitFileBean.pamr = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe35.jpg'
      }
    ];
    this.unitFileBean.namr = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe36.jpg'
      }
    ];
    this.unitFileBean.cpam = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe37.jpg'
      }
    ];
    this.unitFileBean.rcam = [
      {
        uid: -1,
        name: 'safe28.jpg',
        status: 'done',
        url: 'assets/images/safe38.jpg'
      }
    ];
  }

  /**
   * 计算电梯文档的完成度
   */
  calculateFilePercent(){
     let completeNums : number = 0;
     let totalNums : number = 0;
     for (let unitFileBeanKey in this.unitFileBean){
       if("ohe" != unitFileBeanKey && "totalohe" != unitFileBeanKey){
         totalNums++;
       }
       console.log("uid ; " +this.unitFileBean[unitFileBeanKey].uid);
       if(this.unitFileBean[unitFileBeanKey].length){
         for(let i of this.unitFileBean[unitFileBeanKey]){
           if(i.uid != -1){
             completeNums++;
           }
         }
       }
     }
     if((completeNums/totalNums)>=1){
       this.fileCompletePercent = 100+"%";
     }else{
       this.fileCompletePercent = Math.round(completeNums / totalNums * 100)  + "%";
     }

  }
  // 保存
  saveEdit() {
    let flag = false;
    // if (
    //   !this.unitFileBean.urc.length ||
    //   !this.unitFileBean.oir.length ||
    //   !this.unitFileBean.pir.length ||
    //   !this.unitFileBean.diur.length ||
    //   !this.unitFileBean.dmr.length ||
    //   !this.unitFileBean.airr.length ||
    //   !this.unitFileBean.err.length ||
    //   !this.unitFileBean.rfar.length ||
    //   !this.unitFileBean.pcsd.length ||
    //   !this.unitFileBean.sic.length ||
    //   !this.unitFileBean.ecp.length
    // ) {
    //   flag = true;
    // }
    if (flag) {
      return this._notification.create(
        "warning",
        "警告提示",
        "抱歉! 带*为必传项，请您务必补充完整信息"
      );
    } else {
      let  partyType = JSON.parse(window.localStorage["user"]).partyType;
      if (partyType != "2") {
         this._notification.create("warning", "警告提示","无修改权限");
         return;
      }
      this.uploadParam = Object.assign({}, this.unitFileBean);
      //格式化bean中参数，只上传url地址
      for (let i in this.unitFileBean) {

        let arr = [];
        if (this.unitFileBean[i].length) {
          for (let k of this.unitFileBean[i]) {
            if(k.uid == -1){
              continue;
            }
            if (k.status == "done") {
              // 回调的图片处理
              if (k["url"]) {
                let url = `${k.name}`;
                arr.push(url);
              } else {
                let url = `${k["response"].data}`;
                arr.push(url);
              }
              // 上传的图片处理
            }
          }
          this.uploadParam[i] = JSON.stringify(arr);
        } else {
          this.uploadParam[i] = "";
        }
      }
      this.uploadParam.elevatorNum = this.elevatorNum;
      this.httpServcie.elevatorUpLoad(this.uploadParam).subscribe(data => {
        if (data.status == 200) {
          this._notification.create("success", "成功提示", "保存成功");
          this.toBack();
        } else {
          this._notification.create("error", "失败提示", data.message);
          return;
        }
      });
    }
  }

  elevatorQuery(param) {
    this.httpServcie.elevatorQuery({"num":param}).subscribe(data => {
      if (data.status == 200) {
        this.handleData(data);
        this.calculateFilePercent();
      } else {
        this._notification.create("error", "失败提示", data.message);
        return;
      }
    });
  }

  toBack() {
    window.history.back();
  }

  // 查询回显图片格式解析
  handleData(data) {
    let ret = data.data.list;
    let arr = [];
    this.initImg();
    for (let i in ret) {
      if (ret[i] != "[]" && ret[i] != "") {
        let arr = JSON.parse(ret[i]);
        for (let j of arr) {
          let uid = new Date();
          this.unitFileBean[i].push({
            uid: uid.getTime(),
            name: j,
            status: "done",
            url: `${this.config.IP + this.config.API.getUpload}/${j}`
          });
        }
      }
    }
  }

  // 移除图片
  nzRemoveFile = (file: UploadFile) => {
    let fileItem = file;
    if (fileItem["status"] == "removed") {
      if (fileItem["url"] && fileItem["url"].includes("http")) {
        this.deleteImg(fileItem.name, "");
      } else {
        this.deleteImg(fileItem["response"]["data"], "");
      }
    }
  };
  //巡检记录查询（物业）跳转
  toinspection() {
    this.router.navigate([
      "/home/inspection-record",
      {
        elevatorId: this.elevatorId,
        elevatorType: this.elevatorTypeId
      }
    ]);
  }
  //维修记录跳转
  tomaintain() {
    this.router.navigate([
      "/home/maintenance-record",
      {
        elevatorId: this.elevatorId
      }
    ]);
  }
  // 维保记录
  toMaintenance() {
    this.router.navigate([
      "/home/maintenace-list",
      { id: this.elevatorNum, elevatorTypeId: this.elevatorTypeId }
    ]);
  }
  // 年度自检
  toSelfCheck() {
    this.router.navigate([
      "/home/self-check",
      {
        elevatorId: this.elevatorId,
        elevatorType: this.elevatorTypeId
      }
    ]);
  }
  //应急救援记录 跳转
  torescue() {
    this.router.navigate([
      "/home/elevator-rescue",
      {
        elevatorId: this.elevatorId
      }
    ]);
  }


  // 删除图片服务
  deleteImg(filedata, type) {
    this.httpServcie.deleteUpload(filedata).subscribe(
      data => {
        if (data["status"] != "200") {
          this._notification.create("error", "错误提示", "删除失败！");
          return;
        }
        for (let i in this.unitFileBean) {
          if (this.unitFileBean[i].length) {
            if (
              this.unitFileBean[i].length == 1 &&
              this.unitFileBean[i][0].status == "removed"
            ) {
              this.unitFileBean[i] = [];
            } else {
              let list = [];
              this.unitFileBean[i].forEach((element, idx) => {
                if (element["status"] == "removed") {
                  this.unitFileBean[i].splice(idx, 1);
                  this.unitFileBean[i] = this.unitFileBean[i];
                  list = this.unitFileBean[i];
                  this.unitFileBean[i] = [];
                }
              });
              list.forEach(element => {
                this.unitFileBean[i].push(element);
              });
            }
          }
        }
        this.editFlag = true;
        if (type == "delete") {
          /*this.unitFileBean.sic = [];*/
          this.unitFileBean.sic = [
            {
              uid: -1,
              name: 'safe10.jpg',
              status: 'done',
              url: 'assets/images/safe10.jpg'
            }
          ];
          this._notification.create(
            "warning",
            "警告提示",
            "安全检验合格证的“下次检验日期”与电梯台账不符，档案无法保存，请重新上传或修改台账的下次检验日期"
          );
        }

        let param = {
          type: '2',
          partyId: JSON.parse(window.localStorage["user"]).partyId,
          empiricValue: '-5',
          content: '删除1份电梯安全技术档案中的资料'
        }
        this.httpServcie.addByUpload(param).subscribe(data => {
        }, err => {
        })
      },
      error => {
        this._notification.create("error", "错误提示", "请求超时！");
        return;
      }
    );
  }

  // 预览图片
  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  };

  nzChange(event) {
    if (event.file.status == "error") {
      this._notification.blank("上传失败", `${event.file.message}`);
    }
    if (event.file.status == "done") {
      this.editFlag = true;
      // 校验安全检验合格证的“下次检验日期”与电梯台账是否符合
      if (this.unitFileBean.sic.length>1) {
        let pathStr = this.unitFileBean.sic[1]["response"]["data"];
        this.httpServcie.getNextCheckDate(pathStr).subscribe(data => {
          if (data.status == 200) {
            let ret1 = this.inValue.nextCheckDate;
            let ret2 = data.data.nextCheckDate;
            if (ret1) {
              ret1 = (ret1 + '').substring(0, 6);
            }
            if (ret2) {
              ret2 = (ret2 + '').substring(0, 6);
            }
            if (ret1 != ret2) {
              this.deleteImg(
                this.unitFileBean.sic[1]["response"]["data"],
                "delete"
              );
            }
          }
        });
      }
      let param = {
        type: '2',
        partyId: JSON.parse(window.localStorage["user"]).partyId,
        empiricValue: '5',
        content: '上传1份电梯安全管理制度中的资料'
      }
      this.httpServcie.addByUpload(param).subscribe(data => {

      }, err => {

      })
    }
  }
}
